﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Babel.ParserGenerator;

namespace dragonangel.phpProject.Language.DSL
{
    public class CodeExpression
    {
        protected CodeExpression() { }

        public CodeExpression(LexLocation b, LexLocation e)
        {
            this.begin = b;
            this.end = e;
        }

        public CodeExpression(LexLocation b, LexLocation e, bool hasMembers)
        {
            this.begin = b;
            this.end = e;
            this.hasMembers = hasMembers;
        }

        protected LexLocation begin;
        public virtual LexLocation Begin
        {
            get { return begin; }
            set { begin = value; }
        }

        protected LexLocation end;
        public virtual LexLocation End
        {
            get { return end; }
            set { end = value; }
        }

        private bool hasMembers = false;

        public bool IsInScope(int line, int col)
        {
            bool isInScope = false;
            isInScope = Begin.sLin < line && End.eLin > line;
            if (!isInScope)
            {
                if (Begin.sLin == line)
                    isInScope = Begin.sCol <= col;
                if (End.eLin == line)
                    isInScope = End.eCol >= col;
            }
            return isInScope;
        }

        public bool IsInScope(LexLocation location)
        {
            return IsInScope(location.sLin, location.sCol) && IsInScope(location.eLin, location.eCol);
        }

        public bool IsInScope(LexLocation begin, LexLocation end)
        {
            bool isInScope = false;
            isInScope = begin.sLin < Begin.sLin && end.eLin > End.eLin;
            if (!isInScope)
            {
                if (Begin.sLin == begin.sLin)
                    isInScope = begin.sCol <= Begin.sCol;
                if (End.eLin == end.eCol)
                    isInScope = end.eCol >= End.eCol;
            }
            return isInScope;
        }

        public bool IsInScope(CodeExpression expression)
        {
            return IsInScope(expression.Begin, expression.End);
        }

        public virtual CodeExpression GetExpression(int line, int col)
        {
            if (IsInScope(line, col))
                return this;
            return null;
        }

        public virtual CodeExpression GetFirstParentContainingMember(int line, int col)
        {
            if (IsInScope(line, col) && this.hasMembers)
                return this;
            return null;
        }

        protected IList<CodeVariable> availableVariablesInScope;

        public IList<CodeVariable> AvailableVariablesInScope
        {
            get { return availableVariablesInScope; }
        }

    }
}
